package com.hua.fanqiemall.product.service.impl;

import com.hua.fanqiemall.product.entity.BrandEntity;
import com.hua.fanqiemall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hua.common.utils.PageUtils;
import com.hua.common.utils.Query;

import com.hua.fanqiemall.product.dao.CategoryDao;
import com.hua.fanqiemall.product.entity.CategoryEntity;
import com.hua.fanqiemall.product.service.CategoryService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 分页查询
     * @author luoweihua
     * @date 2022/1/10 23:09
     * @param params
     * @return PageUtils
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().ne("show_status",0));
        if(categoryEntityList!=null && categoryEntityList.size()>0) {
             return categoryEntityList.stream().filter(
                    mean -> mean.getParentCid().equals(0L)
            ).peek(
                    mean-> mean.setChildrens(getChildrens(mean.getCatId(),categoryEntityList))
             ).sorted(
                     Comparator.comparingInt(mean -> (mean.getSort() == null ? 0 : mean.getSort()))
             ).collect(Collectors.toList());
        }
        return categoryEntityList;
    }

    /**
     * 根据id列表删除菜单
     * @author luoweihua
     * @date 2021/12/13 23:05
     * @param list
     * @return Boolean
     */
    @Override
    public Boolean removeMenuByIds(List<Long> list) {
        //TODO 检查当前删除的菜单，是否被别的地方引用
        //逻辑删除
        for (Long id : list) {
            CategoryEntity categoryEntity = new CategoryEntity();
            categoryEntity.setCatId(id);
            categoryEntity.setShowStatus(0);
            int result = baseMapper.updateById(categoryEntity);
        }
        return true;
    }

    /**
     * 根据目录id获取目录完整路径
     * @author luoweihua
     * @date 2022/1/5 22:38
     * @param catelogId
     * @return Long[]
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, path);
        Collections.reverse(path);
        return parentPath.toArray(new Long[0]);
    }

    /**
     * 级联更新所有关联的数据
     * @author luoweihua
     * @date 2022/1/10 22:57
     * @param category
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);

        if (StringUtils.isNotEmpty(category.getName())){
            categoryBrandRelationService.updateCategory(category.getCatId() , category.getName());
        }
    }

    private List<Long> findParentPath(Long catelogId , List<Long> path){
        path.add(catelogId);
        CategoryEntity entity = this.getById(catelogId);
        if (entity.getParentCid() != 0){
            findParentPath(entity.getParentCid(),path);
        }
        return path;
    }

    private List<CategoryEntity> getChildrens(Long rootId,List<CategoryEntity> allList){
        return allList.stream().filter(
                entity->entity.getParentCid().equals(rootId)
        ).peek(
                mean -> mean.setChildrens(getChildrens(mean.getCatId(),allList))
        ).sorted(
                Comparator.comparingInt(mean -> (mean.getSort() == null ? 0 : mean.getSort()))
        ).collect(Collectors.toList());
    }
}